<template>
  <div class="page-form">
    <div class="ad-block card">
<!--      <div class="item"><span class="label">公司名称：</span>{{}}</div>-->
      <div class="item"><span class="label">结算人：</span>{{query[0] && query[0].settlementUser}}</div>
      <div class="item"><span class="label">结算电话：</span>{{query[0] && query[0].settlementPhone}}</div>
      <div class="item-l"></div>
      <div class="item"><span class="label">未收合计：</span>{{query.reduce((total, { unCollection }) => total + unCollection, 0)}}</div>
      <div class="item"><span class="label">未付合计：</span>{{query.reduce((total, { unPayment }) => total + unPayment, 0)}}</div>
      <div class="item"><span class="label">应结款：</span>{{query.reduce((total, { financeCheck }) => total + financeCheck, 0)}}</div>
    </div>
    <div class="ad-block card">
      <el-form :model="form" ref="form" style="flex-direction: row">
        <div class="col" style="margin-top: 0">
          <div class="col-title">凭证</div>
          <el-form-item prop="imgList" :rules="{required: true, message:'请上传凭证'}">
            <el-upload action="" list-type="picture-card" multiple drag
                       :file-list="images"
                       :on-success="imageSuccess"
                       :http-request="uploadImages"
                       :on-remove="removeImage"
                       :on-preview="imagePreview"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </div>
        <div>
          <div class="col">
            <div class="col-title">收付款时间</div>
            <div class="item">
              <el-form-item prop="realCollectionTime">
                <el-date-picker size="mini"  placeholder="请选择" v-model="form.realCollectionTime" value-format="timestamp" type="datetime" />
              </el-form-item>
            </div>
          </div>
          <div class="col">
            <div class="col-title">渠道</div>
            <div class="item">
              <el-form-item prop="channel" :rules="{required: true, message:'请选择渠道'}">
                <el-select v-model.number="form.channel" clearable>
                  <el-option v-for="type in dict.finance_channel" :key="type.id" :label="type.label" :value="Number(type.value)"/>
                </el-select>
              </el-form-item>
            </div>
          </div>
          <div class="col">
            <div class="col-title">备注</div>
            <div class="item">
              <el-form-item prop="remark">
                <el-input size="mini" placeholder="" v-model="form.remark" style="width: 300px" />
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
    </div>
    <div class="card" style="padding: 0">
      <ad-table :data="query" border u-table>
        <ad-table-column label="子订单号" prop="orderSubNo"/>
        <ad-table-column label="运单号" prop="transportNo"/>
        <ad-table-column label="大板车牌" prop="licensePlateNumber"/>
        <ad-table-column label="制单人" prop="createUserName"/>
        <ad-table-column label="制单时间" prop="createTime" ctype="datetime"/>
        <ad-table-column label="客户" prop="customerName"/>
        <ad-table-column label="联系电话" prop="customerPhone"/>
        <ad-table-column label="收货人" prop="consigneeName"/>
        <ad-table-column label="联系电话" prop="consigneePhone"/>
        <ad-table-column label="出发地" prop="startCode" ctype="city"/>
        <ad-table-column label="目的地" prop="destinationCode" ctype="city"/>
        <ad-table-column label="车型名称" prop="carName"/>
        <ad-table-column label="车架号" prop="vin"/>
        <ad-table-column label="未收运费" prop="unCollection"/>
        <ad-table-column label="未付商务费" prop="kickbackUn"/>
        <ad-table-column label="未付提车费" prop="pickUn"/>
        <ad-table-column label="未付承运费" prop="transportUn"/>
        <ad-table-column label="未付送车费" prop="takeUn"/>
        <ad-table-column label="未付其他费用" prop="otherUn"/>
        <ad-table-column label="未付费用合计" prop="unPayment"/>
        <ad-table-column label="应结款" prop="financeCheck"/>
      </ad-table>
    </div>
    <div class="op fix-bottom">
      <el-button type="primary" :loading="saving" @click="reconciliation({redirect: '/order/all'})">对 账</el-button>
      <el-button type="primary" :loading="saving" @click="save({redirect: '/order/all'})">保 存</el-button>
    </div>

    <el-dialog append-to-body :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl">
    </el-dialog>
  </div>
</template>

<script>
import qs from 'qs'
import AdTable from '@/components/AdTable'
import AdTableColumn from '@/components/AdTable/AdTableColumn'
import { parseTime } from '@/utils'
import { parseStatus, parseCityCode } from '@/utils/code'
import aliOSS from '@/utils/aliOss'
import { get, add,reconciliation } from '@/api/finance/check/wait'

export default {
  name: 'finance-check-wait-index',
  components: { AdTable, AdTableColumn },
  dicts: ['payment_type','finance_channel'],
  data() {
    return {
      query: [],
      saving: false,
      form: {
        imgList: [],
        realCollectionTime: new Date().getTime(),
        remark: ''
      },
      images: [],
      dialogVisible: false,
      dialogImageUrl: ''
    }
  },
  watch: {
    $route :{
      handler(to, from){
        if((from&&from.path === '/finance/settlement')&&to.path!=='/finance/settlement'){
          return
        }

        let query
        if (to.query.settlementIdList) {
          query = to.query.settlementIdList
        } else {
          query = 'checkTransportNo=' + (to.query.checkTransportNo || '')
        }

        // get(query + this.$route.query.orderSearchQuery).then(res => {
        get(query).then(res => {
          this.query = JSON.parse(to.query.ids).map(id => res.data.list.filter(row => row.orderId == id)).flat()
        })
      }
     ,
      immediate: true
    }
  },
  methods: {
    parseTime, parseStatus, parseCityCode,
    async uploadImages(file) {
      return aliOSS.ossUploadFile(file, 'image')
    },
    imageSuccess(res, file, fileList) {
      this.images = fileList
      this.form.imgList = this.images.map(img => img.response.data)
      this.$refs.form.clearValidate('imgList')
    },
    removeImage(file, fileList) {
      this.deletedImages.push(file.url.split('/').reduce((cur, next, index) => {
        if (index >= 3) {
          return cur ? cur + '/' + next : next
        } else {
          return ''
        }
      }))
      this.images = fileList
    },
    imagePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    save() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // this.$confirm('确定保存吗？','保存').then(res => {
            this.saving = true
            const settlementIdList = qs.parse(this.$route.query.settlementIdList).settlementIdList
            add({
              settlementIdList: settlementIdList && (Array.isArray(settlementIdList) ? settlementIdList : [settlementIdList]),
              orderIdList: this.query.map(item => item.orderId),
              beginSearchTime: this.query.beginSearchTime,
              endSearchTime: this.query.endSearchTime,
              transportNo: this.$route.query.checkTransportNo,
              imageList: this.images.map(img => img.response.data),
              realCollectionTime: this.form.realCollectionTime,
              channel: this.form.channel,
              remark: this.form.remark
            }).then(res => {
              this.$router.push({path: '/wait/index', query: {name: this.$route.query.name}})
            }).finally(() => {
              this.saving = false
            })
          // })
        }
      })
    },
    reconciliation() {
      // this.$refs.form.validate(valid => {
        // if (valid) {
          // this.$confirm('确定保存吗？','保存').then(res => {
          this.saving = true
          const settlementIdList = qs.parse(this.$route.query.settlementIdList).settlementIdList
          reconciliation({
            settlementIdList: settlementIdList && (Array.isArray(settlementIdList) ? settlementIdList : [settlementIdList]),
            orderIdList: this.query.map(item => item.orderId),
            beginSearchTime: this.query.beginSearchTime,
            endSearchTime: this.query.endSearchTime,
            transportNo: this.$route.query.checkTransportNo,
            imageList: this.images.map(img => img.response.data),
            realCollectionTime: this.form.realCollectionTime,
            channel: this.form.channel,
            remark: this.form.remark
          }).then(res => {
            this.$router.push({path: '/wait/index', query: {name: this.$route.query.name}})
          }).finally(() => {
            this.saving = false
          })
          // })
        // }
      // })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-form-item__content { margin-left: 0; line-height: 26px; }
::v-deep .el-select .el-input__inner { font-size: 12px; }
.op.fix-bottom { padding-right: 20px; justify-content: flex-end; }
.page-form { padding: 20px 20px 70px; }
.ad-block { margin-bottom: 20px; }
</style>

<style lang="stylus" scoped>
.dialog-content
  padding 20px
.card
  font-size 12px
  display flex
  padding 16px 20px
  // overflow hidden
  .item-l
    position relative
    float left
    width 40px
    height 1px
    &:before
      content ''
      display block
      position absolute
      top -5px
      width 1px
      height 28px
      background #eaeaea
  .el-form
    display flex
    flex-direction column
    .col
      margin-top 18px
      padding-left 0
      border-right none
  // &:first-child
  //   margin-top 0
  .item
    float left
    margin-right 36px
  .group
    float left
  .col
    float left
    border-right 1px solid #f5f5f5
    padding 0 34px
    &:first-child
      padding-left 0
    &:last-child
      padding-right 0
      border-right 0
    .col-title
      margin-bottom 12px
    .item
      float none
      margin-bottom 16px
      margin-right 0
      &:last-child
        margin-bottom 0
    .el-form-item
      display inline-block
      margin-bottom 0
  /deep/.el-upload-list__item
  /deep/.el-upload--picture-card
    width 90px
    height 54px
    line-height 58px
    .el-upload-dragger
      width 100%
      height 100%
      border none
.form-btns
  text-align center
/deep/.el-select
  input
    height 28px
  .el-input__icon
    line-height 28px
</style>
